# -*- coding: utf-8 -*-
# Copyright © 2015 Beijing HengXingChangDa Technology Co., Ltd. All rights reserved.


from django.http import HttpResponse
# from django.core.exceptions import
from mjs.settings import DEBUG
import json
from django.views.decorators.csrf import ensure_csrf_cookie
from utils.tools import *
from utils.error import Error


class BadRequest(HttpResponse):
    status_code = 400


class NotFound(HttpResponse):
    status_code = 404


class Forbidden(HttpResponse):
    status_code = 403


class NotAllowed(HttpResponse):
    status_code = 405


@ensure_csrf_cookie
def get_csrf(request):
    return HttpResponse("done")


STATS_NUM_LIST = [
    {'text': '10',},
    {'text': '20', 'selected': True},
    {'text': '30',},
    {'text': '40',},
    {'text': '50'},
    {'text': '100'},
    {'text': '全部'},
]


def stats_num_list(request):
    return response_json(STATS_NUM_LIST)


RETAILER_TYPES = [
    {'text': '全部', 'type': '0', 'selected': True},
    {'text': '平台商', 'type': '1'},
    {'text': '代理商', 'type': '2'},
]


def retailer_types(request):
    return response_json(RETAILER_TYPES)


def get_request(request, method):
    """
    This function helps to set the request handler
    where to parse the request info.
    """
    if DEBUG or method == 'ALL':
        d = request.GET.copy()
        d.update(request.POST)
        return d
    if method == 'GET':
        return request.GET
    if method == 'POST':
        return request.POST
    raise NotAllowed


def get_retailer(request):
    user = request.user
    groups = user.groups.all()
    # KEIS_ASSERT(groups)
    # KEIS_ASSERT(groups.count() == 1)
    return groups[0].department.retailer


def response_json(obj, encoder=None, response_type=HttpResponse):
    return HttpResponse(
        json.dumps(obj,
                   default=encoder,
                   indent=4,
                   #separators=(',',':'),
                   ensure_ascii=False),
        content_type="application/json;charset=utf-8")
        # content_type="text/html;charset=utf-8")


def response_json2(obj, encoder=None, response_type=HttpResponse):
    return HttpResponse(
        json.dumps(obj,
                   default=encoder,
                   indent=4,
                   # separators=(',',':'),
                   ensure_ascii=False),
        content_type="application/json;charset=utf-8")


def response_json_table(objects, total_count, detail=True, real_object=None):
    object_array = []
    for obj in objects:
        if real_object:
            object_array.append(real_object(obj).to_dict(detail))
        else:
            object_array.append(obj.to_dict(detail))
    table = dict()
    table['rows'] = object_array
    # table['total'] = len(object_array)
    table['total'] = total_count
    return response_json(table)


def response_error(msg, response_type=HttpResponse):
    errmsg = dict()
    errmsg['Error'] = msg
    return response_json(errmsg, response_type=response_type)


def response_message(msg, response_type=HttpResponse):
    response_msg = dict()
    response_msg['Message'] = msg
    return response_json(response_msg, response_type=response_type)


def response_code(code, add_msg=None, response_type=HttpResponse):
    return response_json(code.to_dict(KEIS_LOCALE, add_msg), response_type=response_type)


def bad_request(code, add_msg=None):
    return response_code(code, add_msg, BadRequest)


def no_perm(code, add_msg=None):
    return response_code(code, add_msg, Forbidden)


def not_found(code, add_msg=None):
    return response_code(code, add_msg, NotFound)

def handle_pagination(req, objects, detail=True, real_object=None):
    if isinstance(objects, list):
        total_count = len(objects)
    else:
        total_count = objects.count()
#     if total_count == 0:
#         total_count = 1
    page = req['page']
    if page.isdigit():
        page = int(page)
        if page > 0:
            rows = req['rows']
            if rows.isdigit():
                rows = int(rows)
                if rows > 0:
                    range_start = ((page - 1) * rows)
                    range_end = page * rows
                    objects = objects[range_start:range_end]
    return response_json_table(objects, total_count, detail, real_object)


def handle_download(objtype, req, objects, detail=True, objarg = None):
    curtime = time.strftime('%Y_%m_%d-%H_%M_%S', time.localtime(time.time()))
    sio = write_data_to_excel(objtype, objects, objarg)
    response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
    f = '%s-%s.xls' % (objtype.excel_name(objarg), curtime)
    filename = urlquote(f)
    response['Content-Disposition'] = "attachment; filename=%s; filename*=utf-8''%s" % (filename, filename)
    return response


def handle_result(objtype, req, objects, detail=True, real_object=None, objarg=None):
    if 'export' in req and req['export'].upper() == 'TRUE':
        return handle_download(objtype, req, objects, detail, objarg)

    if 'page' in req and 'rows' in req:
        return handle_pagination(req, objects, detail, real_object)
    object_array = []
    for obj in objects:
        if real_object:
            object_array.append(real_object(obj).to_dict(detail))
        else:
            object_array.append(obj.to_dict(detail))
    return response_json(object_array)

